package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.ShopBean;
import com.project.mapper.IShopMapper;
import com.project.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ShopServiceImpl implements IShopService {
    @Autowired
    private IShopMapper mapper;
    @Override
    public void add(int productId, int userId) {
        QueryWrapper<ShopBean> qw = new QueryWrapper<>();
        qw.eq("fk_productId",productId);
        qw.eq("fk_userId",userId);

        //按用户ID和商品ID查询购物车对象
        ShopBean shopBean = mapper.selectOne(qw);
        if(shopBean == null){//该用户没有购买该商品，新加购物车记录
            shopBean = new ShopBean(userId,productId);
            mapper.insert(shopBean);
        }
        else{//该用户购物车已有该商品，则数量加一
            shopBean.setNum(shopBean.getNum() + 1);
            mapper.updateById(shopBean);
        }
    }

    @Override
    public List<ShopBean> findByUser(int userId) {

        return mapper.findByUser(userId);
    }

    @Override
    public void del(int cartId) {
        mapper.deleteById(cartId);
    }

    @Override
    public void updateNum(int cartId, Integer newNum) {
        ShopBean shopBean = new ShopBean();
        shopBean.setId(cartId);
        shopBean.setNum(newNum);
        mapper.updateById(shopBean);
    }
}
